package com.greateffect.littlebud.lib.base;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.greateffect.littlebud.lib.R;
import com.greateffect.littlebud.lib.cache.CustomExtraKeys;
import com.greateffect.littlebud.lib.di.component.AppComponent;
import com.greateffect.littlebud.lib.dialog.CustomDialogHelper;
import com.greateffect.littlebud.lib.imageloader.ImageLoader;
import com.greateffect.littlebud.lib.listener.OnCommonListener;
import com.greateffect.littlebud.lib.mvp.IPresenter;
import com.greateffect.littlebud.lib.mvp.IViewAdvance;
import com.greateffect.littlebud.lib.ui.BaseActivity;
import com.greateffect.littlebud.lib.utilcode.BarUtils;
import com.greateffect.littlebud.lib.utilcode.ToastUtils;
import com.greateffect.littlebud.lib.utils.NetworkUtil;

import org.greenrobot.eventbus.EventBus;

import javax.inject.Inject;

/**
 * Created by ZengCS on 2019/1/24.
 * function：BaseNormalFragmentAdv
 */
public abstract class BaseNormalFragmentAdv<P extends IPresenter> extends Fragment implements IViewAdvance {
    protected final String TAG = this.getClass().getSimpleName();
    private BaseActivity mActivity;
    protected View mRootView;
    protected boolean hasInit = false;

    @Inject
    protected P mPresenter;

    protected boolean isLoading = false;
    private Dialog progressDialog;
    protected ImageLoader imageLoader;
    protected String mAppName;
    protected boolean isGoToAppSettings;

    protected OnCommonListener onCommonListener;

    protected void setToolbarPaddingWhenTransStatusBar(ViewGroup toolbarLayout) {
        if (toolbarLayout == null) return;
        toolbarLayout.setPadding(0, BarUtils.getStatusBarHeight(), 0, 0);
    }

    /**
     * 提供AppComponent(提供所有的单例对象)给子类，进行Component依赖
     *
     * @param appComponent
     */
    protected abstract void setupFragmentComponent(AppComponent appComponent);


    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    @Override
    public void onDestroy() {
        hideLoading();
        progressDialog = null;

        super.onDestroy();
        if (mPresenter != null) mPresenter.onDetach();//释放资源
        if (useEventBus())//如果要使用eventbus请将此方法返回true
            EventBus.getDefault().unregister(this);
        this.mPresenter = null;
        this.mActivity = null;
        this.mRootView = null;
    }

    /**
     * 是否使用eventBus,默认为使用(true)，
     *
     * @return
     */
    public abstract boolean useEventBus();


    protected abstract void initData();

    protected abstract void getDataFromNet();

    public BaseActivity getBaseActivity() {
        return mActivity;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mActivity = (BaseActivity) getActivity();
        //使用了eventbus并且未注册时
        if (useEventBus() && !EventBus.getDefault().isRegistered(this))//如果要使用eventbus请将此方法返回true
            EventBus.getDefault().register(this);//注册到事件主线
        setupFragmentComponent(mActivity.mApplication.getAppComponent());
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if (!isHidden()) {
            hasInit = true;
            initData();
        }
        mAppName = getString(R.string.app_name);
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden && !hasInit) {
            hasInit = true;
            initData();
        }
    }

    @Override
    public void showLoading() {
        showLoading(getString(R.string.txt_loading_common));
    }

    @Override
    public void hideLoading() {
        isLoading = false;
        if (progressDialog != null && progressDialog.isShowing())
            progressDialog.dismiss();
    }

    @Override
    public void showMessage(String message) {
        hideLoading();
        CustomDialogHelper.showCustomMessageDialog(getBaseActivity(), message);
    }

    @Override
    public void launchActivity(Intent intent) {
        startActivity(intent);
    }

    @Override
    public void launchActivity(Class clz) {
        launchActivity(clz, null);
    }

    @Override
    public void launchActivity(Class clz, String param) {
        Intent intent = new Intent(getBaseActivity(), clz);
        if (!TextUtils.isEmpty(param))
            intent.putExtra(CustomExtraKeys.KEY_STRING, param);
        launchActivity(intent);
    }

    @Override
    public boolean isNetworkConnected() {
        return NetworkUtil.isConnected();
    }

    @Override
    public void killMyself() {

    }

    @Override
    public void showLoading(String msg) {
        // 显示Loading框
        forceShowLoading(msg);
    }

    @Override
    public void forceShowLoading(String msg) {
        if (progressDialog == null) {
            View view = LayoutInflater.from(getBaseActivity()).inflate(R.layout.dialog_custom_loading, null);
            TextView tips = view.findViewById(R.id.tv_tip);
            tips.setText(msg);

            progressDialog = new Dialog(getBaseActivity(), R.style.CustomDialogWithDim);
            progressDialog.setContentView(view);
            progressDialog.setCancelable(false);
            progressDialog.setCanceledOnTouchOutside(false);
        } else {
            TextView tips = progressDialog.findViewById(R.id.tv_tip);
            tips.setText(msg);
        }
        if (!progressDialog.isShowing()) {
            progressDialog.show();
        }
    }

    @Override
    public void showToast(String message) {
        if (TextUtils.isEmpty(message)) return;
        ToastUtils.showLong(message);
    }

    //显示错题提示信息
    protected void showLoadErrorMsg(String errorMsg) {
        if (TextUtils.isEmpty(errorMsg)) {
            errorMsg = getString(R.string.txt_load_data_error);
        }
        showToast(errorMsg);
    }

    @Override
    public void showShortcutMenu() {

    }

    @Override
    public void hideShortcutMenu() {

    }

    @Override
    public void hideSoftInput() {

    }

    @Override
    public Context getAttachedContext() {
        return getContext();
    }


    public <T> void setOnCommonListener(OnCommonListener<T> onCommonListener) {
        this.onCommonListener = onCommonListener;
    }

    /**
     * 获取字符串资源
     *
     * @param stringId
     * @return
     */
    protected String getStringValue(int stringId, Object... params) {
        return getBaseActivity().getResources().getString(stringId, params);
    }

    /**
     * fragment对用户是否可见
     */
    public boolean isVisibleToUser() {
        return isResumed() && getUserVisibleHint();
    }
}
